package pers.supeijin.devtools.converter;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.SystemIndependent;

import java.io.File;

import pers.supeijin.devtools.converter.wx2vue.WeiXin2VueHelper;
import pers.supeijin.devtools.utils.FileUtils;
import pers.supeijin.devtools.utils.GeneralContext;

/**
 * @author supeijin
 * @date 2020/2/20.
 */
public class WeiXin2VueAction extends AnAction {
	private static final String VUE_FILE_NAME="App.vue";
	private static final String SRC_FILE_NAME="src";
	private GeneralContext mGeneralContext;
	private static VirtualFile mSelectedVirtualFile;
	@Override
	public void update(@NotNull AnActionEvent e) {
		super.update(e);
		mGeneralContext = new GeneralContext(e);
		boolean enabled = false;
		VirtualFile virtualFile = mGeneralContext.getVirtualFile();
		if(virtualFile !=null && virtualFile.isDirectory()){
			PsiFile psiFile = FileUtils.getFileFromProject(mGeneralContext.getProject(), virtualFile, VUE_FILE_NAME);
			enabled=psiFile!=null;
		}
		mGeneralContext.setEnabledAndVisible(enabled);
	}

	@Override
	public void actionPerformed(AnActionEvent e) {
		Project project = mGeneralContext.getProject();
		final FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
		descriptor.setTitle("请选择");
		descriptor.setShowFileSystemRoots(true);
		descriptor.setDescription("选择需要导入的微信页面或组件文件夹");
		descriptor.setHideIgnored(true);
		descriptor.setForcedToUseIdeaFileChooser(true);
		VirtualFile defaultVirtualFile= mSelectedVirtualFile!=null?mSelectedVirtualFile:project.getWorkspaceFile();
		mSelectedVirtualFile = FileChooser.chooseFile(descriptor, project,defaultVirtualFile );
        if(mSelectedVirtualFile==null){
			Messages.showErrorDialog("你没有选中文件夹","提示");
		}else{
			new WeiXin2VueHelper(mGeneralContext,mSelectedVirtualFile);
		}
	}
	private boolean isSupportProject() {
		@SystemIndependent String basePath = mGeneralContext.getProject().getBasePath();
		String vueFilePath_1 = basePath+ File.separator+SRC_FILE_NAME+File.separator+VUE_FILE_NAME;
		String vueFilePath_2 = basePath+ File.separator+VUE_FILE_NAME;
		String[] paths=new String[]{vueFilePath_1,vueFilePath_2};
		for (int i = 0,len=paths.length; i <len ; i++) {
			File file = new File(paths[i]);
			if(file.exists()){
				return true;
			}
		}
		return false;
	}
}
